package model

import (
	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"gm/app/lib"
	"log"
	"time"
)

type User struct {
	Name string
	Age int
	Sex uint8
}

type Teachuser struct {
	Name string `json:"name"`
	Uid int `json:"uid"`
	Sex uint8 `json:"sex"`
}


type Gift struct {
	Name string
}

type PlayActiveManage2 struct {
	Cname string
}


var DB *gorm.DB

func InitDB(conf lib.ServerConfig) {
	var err error
	dbParams := fmt.Sprintf("%v:%v@tcp(%v)/%v?charset=utf8&loc=Local",
		conf.User,
		conf.Password,
		conf.Host,
		conf.DbName,
	)
	DB, err = gorm.Open("mysql", dbParams)

	if err != nil {
		log.Fatal(2, err)
	}

	// 全局禁用表名复数
	DB.SingularTable(true)
	//启用Logger，显示详细日志，默认情况下会打印发生的错误
	DB.LogMode(true)
	gorm.DefaultTableNameHandler = func(db *gorm.DB, defaultTableName string) string {
		return conf.TablePrefix + defaultTableName
	}

	DB.SingularTable(true)
	//DB.Callback().Create().Replace("gorm:update_time_stamp", updateTimeStampForCreateCallback)
	//DB.Callback().Update().Replace("gorm:update_time_stamp", updateTimeStampForUpdateCallback)
	//DB.Callback().Delete().Replace("gorm:delete", deleteCallback)

	//默认支持 连接池管理
	DB.DB().SetMaxIdleConns(10) //最大空闲连接数
	DB.DB().SetMaxOpenConns(100)//最大连接数
	DB.DB().SetConnMaxLifetime(time.Second * 300) //设置连接空闲超时
	fmt.Println("database init on port ", conf.Host)
}




func AddUser(name string,  age int) error {
	DB, _ := gorm.Open("mysql", "root:123456@/dev?charset=utf8&parseTime=True&loc=Local")
	DB.SingularTable(true)

	user := User{
		Name:  name,
		Age:    age,

	}
	if err := DB.Create(&user).Error; err != nil {
		return err
	}
	return nil
}


func UptUser(id int, data interface{}) error {
	DB, _ := gorm.Open("mysql", "root:123456@/dev?charset=utf8&parseTime=True&loc=Local")
	DB.SingularTable(true)
	if err := DB.Model(&User{}).Where("id = ? AND enable = ? ", id, 1).Updates(data).Error; err != nil {
		return err
	}

	return nil
}


func GetNewOrders(id int) ([]User, error) {
	DB, _ := gorm.Open("mysql", "root:123456@/dev?charset=utf8&parseTime=True&loc=Local")
	DB.SingularTable(true)
	var user []User
	DB.First(&user)

	println(456)
	return user, nil
}









